package com.zkh.myframe.database.mapper.parser;

import java.math.BigDecimal;

import com.zkh.myutils.utils.Regexp;
import com.zkh.myutils.utils.StringUtils;

/**
 * 参数值，Include传参专用（暂时）
 * @author zkh
 */
public class ParamValue {
	//值表达式或值
	private String expression;
	private Object value;
	//值类型
	private ParamValueType type;
	//是否占位符
	private boolean placeholder;
	
	private ParamValue() {}

	private ParamValue(String expression, Object value, ParamValueType type) {
		this.expression = expression;
		this.value = value;
		this.type = type;
	}
	
	/**
	 * 将字符串解析为ParamValue对象
	 * @param value 待解析的值
	 */
	public static ParamValue parseValue(String value) {
		//初始化ParamValue对象
		ParamValue pv = new ParamValue();
		//为空
		if(value==null) {
			pv.setValue(null);
		}else if(Regexp.isMatch("#\\{\\s*.+\\s*\\}", value)){
			pv.setExpression(Regexp.getMatchOne("(?<=#\\{).+(?=\\})", value).trim(), ParamValueType.VARIABLE);
			pv.setPlaceholder(true);
		} else if(Regexp.isMatch("\\$\\{\\s*((\\w+(\\[\\d+\\])?(\\.\\w+(\\[\\d+\\])?)*)|(@\\w+(\\.\\w+)*@\\w+(\\.\\w+(\\(\\))?)?))\\s*\\}", value)){
			//$#开头，获取核心方法
			String tvalue = Regexp.getMatchOne("(?<=\\$\\{).+(?=\\})", value).trim();
			//不是以“@”开始，为变量
			if(!tvalue.startsWith("@")) {
				pv.setExpression(tvalue, ParamValueType.VARIABLE);
			}
			//静态变量或方法
			else {
				//去掉开头@并以@分割。结果为 [类名，方法或属性]
				String[] elems = tvalue.substring(1).split("@");
				//检查是否是枚举值（方法或属性包含点）
				String[] enumElems = elems[1].split("\\.");
				//长度为1，说明是普通的静态方法
				if(enumElems.length==1) {
					//检查是否是常量，常量直接获取，变量则动态获取值
					if(ParseUtils.isFinalVariable(elems[0], elems[1])) {
						pv.setValue(ParseUtils.getFieldValue(elems[0], elems[1]));
					}else {
						pv.setExpression(elems[0]+"@"+elems[1], ParamValueType.STATICFIELD);
					}
				}else {
					//枚举值，直接获取枚举值
					pv.setValue(ParseUtils.getEnumValue(elems[0], enumElems[0], enumElems[1], Object.class));
				}
			}
		}else {
			//值，字符或数字
			pv.setValue(StringUtils.isNumeric(value) ? new BigDecimal(value) : value);
		}
		//以@开头
		return pv;
	}

	public String getExpression() {
		return expression;
	}
	public void setExpression(String expression, ParamValueType type) {
		this.expression = expression;
		this.type = type;
	}
	public ParamValueType getType() {
		return type;
	}
	public void setType(ParamValueType type) {
		this.type = type;
	}
	public Object getValue() {
		return value;
	}
	public boolean isPlaceholder() {
		return placeholder;
	}

	public void setPlaceholder(boolean placeholder) {
		this.placeholder = placeholder;
	}

	@Override
	public String toString() {
		return "ParamValue [expression=" + expression + ", value=" + value + ", type=" + type + ", placeholder="
				+ placeholder + "]";
	}

	/**
	 * 设置ParamValueType.FIXVALUE类型的值
	 */
	public void setValue(Object value) {
		this.value = value;
		this.type = ParamValueType.FIXVALUE;
	}
}
